package com.projects.android;

import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.projects.android.bus.UsersBUS;
import com.projects.android.bus.ValidationBUS;
import com.projects.android.utils.CommonFlags;
import com.projects.android.utils.SelectedItems;
import com.projects.android.utils.Settings;
import com.projects.android.utils.Utils;
import com.projects.android.views.Configuration;
import com.projects.android.views.Login;

public class Intro extends Activity implements OnClickListener {
	private ImageView imgIntro;

	// For user not login
	private Button btnLogin;
	private Button btnRegister;
	private Button btnForgotPassword;
	// For user logged in
	private Button btnStartOrder;
	private Button btnLogOff;
	private Button btnUpdateInformation;
	private Button btnChangePassword;

	private Button btnExit;
	private Intent intent;
	private Login dlgLogin;
	private final int HEIGHT = 40;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.intro);
		// Init logging for project
		initView();
		// Load server address from setting
		Utils.SERVICE_URI = Settings.loadPreference(this);
		if (!CommonFlags.SettingConfigurated) {
			fetchNewData();
		}
	}

	public boolean checkAddress() {
		try {
			String url = Utils.SERVICE_URI + "/TestService";
			// Send GET request to <service>/GetPlates
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet request = new HttpGet(new URI(url));
			request.setHeader("Accept", "application/json");
			request.setHeader("Content-type", "application/json");

			HttpResponse response = httpClient.execute(request);
			HttpEntity responseEntity = response.getEntity();
			// Read response data into buffer
			String result = Utils.getResponse(responseEntity);
			Log.i("checkAddress", "Response: " + result);

			if (result != "") {
				return true;
			}
		} catch (Exception e) {
			Log.e("loadDataCheck", e.toString());
		}

		return false;
	}

	private void fetchNewData() {
		final Configuration serverDialog = new Configuration(this,
				Utils.SERVICE_URI);
		serverDialog.setTitle("Server Address");
		serverDialog.setCancelable(true);
		serverDialog.show();
		Button btnAddServer = serverDialog.getBtnSave();

		btnAddServer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.append(serverDialog.getTxtServerAddress()
						.getText());
				Utils.SERVICE_URI = stringBuilder.toString();
				if (Utils.SERVICE_URI.equals("")) {
					AlertDialog dlg = Utils.showAlertDlg(Intro.this,
							"Server Address", "Server Adress is empty");
					dlg.show();
				} else {
					final ProgressDialog dialog = new ProgressDialog(Intro.this);
					dialog.setTitle("Loading. Please wait...");
					dialog.setIndeterminate(true);

					final Thread thread = new Thread(new Runnable() {
						@Override
						public void run() {
							runOnUiThread(new Runnable() {
								final boolean result = checkAddress();

								@Override
								public void run() {
									// Invisible progress dialog
									dialog.dismiss();

									if (result) {
										Settings.savePreference(
												Utils.SERVICE_URI, Intro.this);
										CommonFlags.SettingConfigurated = true;
										serverDialog.dismiss();
									} else {
										AlertDialog dlg = Utils
												.showAlertDlg(Intro.this,
														"Server Address",
														"Cannot connect to service address");
										dlg.show();
									}
								}
							});
						}
					});
					dialog.show();
					thread.start();
				}
			}
		});
	}

	public void setButtonsState(boolean loginStatus) {
		// Not login
		if (!loginStatus) {
			btnStartOrder.setVisibility(View.GONE);
			btnLogOff.setVisibility(View.GONE);
			btnUpdateInformation.setVisibility(View.GONE);
			btnChangePassword.setVisibility(View.GONE);

			btnLogin.setVisibility(View.VISIBLE);
			btnRegister.setVisibility(View.VISIBLE);
			btnForgotPassword.setVisibility(View.VISIBLE);

			btnStartOrder.getLayoutParams().height = 0;
			btnLogOff.getLayoutParams().height = 0;
			btnUpdateInformation.getLayoutParams().height = 0;
			btnChangePassword.getLayoutParams().height = 0;

			btnLogin.getLayoutParams().height = HEIGHT;
			btnRegister.getLayoutParams().height = HEIGHT;
			btnForgotPassword.getLayoutParams().height = HEIGHT;

			imgIntro.getLayoutParams().height = Utils.SCREEN_HEIGHT
					- btnLogin.getLayoutParams().height
					- btnRegister.getLayoutParams().height
					- btnForgotPassword.getLayoutParams().height
					- btnExit.getLayoutParams().height - 20;
		} else {// Logged in
			btnLogin.setVisibility(View.GONE);
			btnRegister.setVisibility(View.GONE);
			btnForgotPassword.setVisibility(View.GONE);

			btnStartOrder.setVisibility(View.VISIBLE);
			btnLogOff.setVisibility(View.VISIBLE);
			btnUpdateInformation.setVisibility(View.VISIBLE);
			btnChangePassword.setVisibility(View.VISIBLE);

			btnLogin.getLayoutParams().height = 0;
			btnRegister.getLayoutParams().height = 0;
			btnForgotPassword.getLayoutParams().height = 0;

			btnStartOrder.getLayoutParams().height = HEIGHT;
			btnLogOff.getLayoutParams().height = HEIGHT;
			btnUpdateInformation.getLayoutParams().height = HEIGHT;
			btnChangePassword.getLayoutParams().height = HEIGHT;

			imgIntro.getLayoutParams().height = Utils.SCREEN_HEIGHT
					- btnStartOrder.getLayoutParams().height
					- btnLogOff.getLayoutParams().height
					- btnUpdateInformation.getLayoutParams().height
					- btnChangePassword.getLayoutParams().height
					- btnExit.getLayoutParams().height - 20;
		}
	}

	private void initView() {
		Display display = getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		int height = display.getHeight();
		Utils.SCREEN_WIDTH = width;
		Utils.SCREEN_HEIGHT = height;
		imgIntro = (ImageView) findViewById(R.id.imgIntro);

		// For user not login
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnRegister = (Button) findViewById(R.id.btnRegister);
		btnForgotPassword = (Button) findViewById(R.id.btnForgotPassword);

		// For user logged in
		btnStartOrder = (Button) findViewById(R.id.btnStartOrder);
		btnLogOff = (Button) findViewById(R.id.btnLogOff);
		btnUpdateInformation = (Button) findViewById(R.id.btnUpdateInformation);
		btnChangePassword = (Button) findViewById(R.id.btnChangePassword);

		btnExit = (Button) findViewById(R.id.btnExit);
		btnExit.getLayoutParams().height = HEIGHT;

		setButtonsState(SelectedItems.SelectedUsers != null
				&& SelectedItems.SelectedUsers.getID() != null
				&& !SelectedItems.SelectedUsers.getID().equals(""));

		imgIntro.getLayoutParams().width = width;

		btnLogin.setOnClickListener(this);
		btnRegister.setOnClickListener(this);
		btnForgotPassword.setOnClickListener(this);

		btnStartOrder.setOnClickListener(this);
		btnLogOff.setOnClickListener(this);
		btnUpdateInformation.setOnClickListener(this);
		btnChangePassword.setOnClickListener(this);

		btnExit.setOnClickListener(this);
	}

	private void login(final String user, final String pass) {
		final ProgressDialog dialog = new ProgressDialog(this);
		dialog.setTitle("Loading. Please wait...");
		dialog.setIndeterminate(true);

		final Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				runOnUiThread(new Runnable() {
					String result = ValidationBUS.validateUser(user, pass);

					@Override
					public void run() {
						dialog.dismiss();
						if (!result.equals("")) {
							updateLoginStatus(result);
						} else {
							dlgLogin.dismiss();
							SelectedItems.SelectedUsers = UsersBUS
									.selectByUserName(user);
							if (SelectedItems.SelectedUsers.getIsLockedOut()) {
								// User is locked out
								SelectedItems.SelectedUsers = null;
								AlertDialog dlg = Utils.showAlertDlg(
										Intro.this, "Warning",
										"User is locked out!");
								dlg.show();
							} else {
								Log.i("User login", "User "
										+ SelectedItems.SelectedUsers.getName()
										+ " loggedin successful");
								setButtonsState(true);
							}
						}
					}
				});
			}
		});
		dialog.show();
		thread.start();
	}

	private void updateLoginStatus(final String status) {
		AlertDialog dlg = Utils.showAlertDlg(this, "Login Status", status);
		dlg.show();
	}

	private boolean validateUserInput(final String user, final String pass) {
		if (user.equals("")) {
			updateLoginStatus("UserName is empty");
			return false;
		} else if (pass.equals("")) {
			updateLoginStatus("Password is empty");
			return false;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnLogin:
			/** Start a new Activity MyCards.java */
			dlgLogin = new Login(this);
			dlgLogin.setTitle("Authentication");
			dlgLogin.show();
			// Login successful
			dlgLogin.getBtnOK().setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (validateUserInput(dlgLogin.getUserName(),
							dlgLogin.getPassword())) {
						login(dlgLogin.getUserName(), dlgLogin.getPassword());
					}
				}
			});
			break;

		case R.id.btnRegister:
			intent = Utils.browseIntent(this, "Register");
			startActivity(intent);
			break;

		case R.id.btnLogOff:
			final ProgressDialog dialog = new ProgressDialog(this);
			dialog.setTitle("Loading. Please wait...");
			dialog.setIndeterminate(true);

			final Thread thread = new Thread(new Runnable() {
				@Override
				public void run() {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							dialog.dismiss();
							SelectedItems.SelectedUsers = null;
							setButtonsState(false);
						}
					});
				}
			});
			dialog.show();
			thread.start();
			break;

		case R.id.btnExit:
			try {
				finalize();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				Log.e("Exit", e.toString());
			}
			this.finish();
			break;

		case R.id.btnStartOrder:
			intent = Utils.browseIntent(this, "Main");
			startActivity(intent);
			break;

		case R.id.btnForgotPassword:
			intent = Utils.browseIntent(this, "ForgotPassword");
			startActivity(intent);
			break;

		case R.id.btnUpdateInformation:
			intent = Utils.browseIntent(this, "UpdateAccount");
			startActivity(intent);
			break;
			
		case R.id.btnChangePassword:
			intent = Utils.browseIntent(this, "ChangePassword");
			startActivity(intent);
			break;
		}
	}
}